package org.opensource.openapi3doc;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

@Configuration
public class OpenAPI3SpecConfig {
    private static Logger logger = LoggerFactory.getLogger(OpenAPI3SpecConfig.class);

    @Autowired
    private Environment env;

    private OAS3Yaml oas3Yaml;

    @Primary
    @Bean
    public SwaggerResourcesProvider swaggerResourcesProvider() {
        oas3Yaml = new OAS3Yaml();
        oas3Yaml.setEnvironment(env);
        oas3Yaml.load();

        return () -> {
            List<SwaggerResource> resources = new ArrayList<>();
            ArrayList<String> yamlNameList = oas3Yaml.getYamlNameList();
            yamlNameList.forEach(resourceName -> resources.add(loadResource(resourceName)));
            return resources;
        };
    }

    private SwaggerResource loadResource(String resource) {
        logger.info("Load yaml resource: " + resource);
        SwaggerResource wsResource = new SwaggerResource();
        wsResource.setName(resource);
        wsResource.setSwaggerVersion("3.0");
        wsResource.setLocation(oas3Yaml.getYamlFile(resource));
        //wsResource.setLocation("/openapi3-apis/" + resource + ".yaml");
        return wsResource;
    }
}
